<template>
  <div class="p-2" style="height: 100%; display: flex; flex-direction: column;">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true">
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="queryParams.roleName" placeholder="请输入角色名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="权限字符" prop="roleKey">
              <el-input v-model="queryParams.roleKey" placeholder="请输入权限字符" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="角色状态" clearable>
                <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="创建时间" style="width: 308px">
              <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :default-time="[new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 1, 1, 23, 59, 59)]"
              ></el-date-picker>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="hover" class="content">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:role:add']" type="primary" plain @click="openAdd()">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:role:edit']" type="success" plain :disabled="single" @click="openUpdate()">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:role:delete']" type="danger" plain :disabled="ids.length === 0" @click="handleDelete()">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['system:role:export']" type="warning" plain @click="handleExport">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table ref="roleTableRef" v-loading="loading" :data="roleList" style="flex: 1;" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="角色名称" prop="roleName" align="center" :show-overflow-tooltip="true" min-width="150" />
        <el-table-column label="权限字符" prop="roleKey" align="center" :show-overflow-tooltip="true" min-width="200" />
        <el-table-column label="显示顺序" prop="roleSort" align="center" width="100" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180" >
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="260" align="center">
          <template #default="scope">
            <el-button v-if="scope.row.roleId != 1" v-hasPermi="['system:role:edit']" link type="primary" @click="openUpdate(scope.row)">
              修改
            </el-button>
            <el-button v-if="scope.row.roleId != 1 && scope.row.dataFrom != 1" v-hasPermi="['system:role:remove']" link type="primary" @click="handleDelete(scope.row)">
              删除
            </el-button>
            <el-button v-if="scope.row.roleId != 1" v-hasPermi="['system:role:edit']" link type="primary" @click="openDataScope(scope.row)">
              数据权限
            </el-button>
            <el-button v-if="scope.row.roleId != 1" v-hasPermi="['system:role:edit']" link type="primary" @click="handleAuthUser(scope.row)">
              分配用户
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-model:total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>

    <!--  新增  -->
    <el-dialog v-model="dialog.showAdd" :title="dialog.title" width="500px" append-to-body destroy-on-close>
      <add @close="dialog.showAdd = false" @success="getList()" ></add>
    </el-dialog>

    <!--  修改  -->
    <el-dialog v-model="dialog.showUpdate" :title="dialog.title" width="500px" append-to-body destroy-on-close>
      <update :role-id="roleId" @close="dialog.showUpdate = false" @success="getList()" ></update>
    </el-dialog>

    <!-- 分配角色数据权限对话框 -->
    <el-dialog v-model="dialog.showDataScope" :title="dialog.title" width="500px" append-to-body destroy-on-close>
      <DataScope :role-id="roleId" @close="dialog.showDataScope = false" />
    </el-dialog>
  </div>
</template>

<script setup  lang="ts">
import { changeRoleStatus, delRole, listRole } from '@/api/system/role';
import update from './components/Update.vue';
import add from './components/Add.vue';
import DataScope from './components/DataScope.vue';

const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { sys_normal_disable } = toRefs<any>(proxy?.useDict('sys_normal_disable'));

const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const queryFormRef = ref<ElFormInstance>();

const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  roleName: '',
  roleKey: '',
  status: ''
});

const dialog = reactive<any>({
  showDataScope: false,
  title: ''
});

/**
 * 查询角色列表
 */
const loading = ref(true);
const roleList = ref<any[]>();
const total = ref(0);
const getList = () => {
  loading.value = true;
  listRole(proxy?.addDateRange(queryParams.value, dateRange.value)).then((res) => {
    roleList.value = res.rows;
    total.value = res.total;
    loading.value = false;
  });
};

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryFormRef.value?.resetFields();
  handleQuery();
};
/** 删除按钮操作 */
const handleDelete = async (row?: any) => {
  const roleids = row?.roleId || ids.value;
  await proxy?.$modal.confirm('是否确认删除角色编号为' + roleids + '数据项目');
  await delRole(roleids);
  getList();
  proxy?.$modal.msgSuccess('删除成功');
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'system/role/export',
    {
      ...queryParams.value
    },
    `role_${new Date().getTime()}.xlsx`
  );
};
/** 多选框选中数据 */
const handleSelectionChange = (selection: any[]) => {
  ids.value = selection.map((item: any) => item.roleId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 角色状态修改 */
const handleStatusChange = async (row: any) => {
  let text = row.status === '0' ? '启用' : '停用';
  try {
    await proxy?.$modal.confirm('确认要"' + text + '""' + row.roleName + '"角色吗?');
    await changeRoleStatus(row.roleId, row.status);
    proxy?.$modal.msgSuccess(text + '成功');
  } catch {
    row.status = row.status === '0' ? '1' : '0';
  }
};

/** 分配用户 */
const handleAuthUser = (row: any) => {
  router.push('/system/role-auth/user/' + row.roleId);
};

/** 分配移动端菜单权限 */
const handleAuthAppMenu = (row: any) => {
  router.push('/system/appMenu-auth/appRoleMenu/' + row.roleId);
};

/** 添加角色 */
const openAdd = () => {
  dialog.showAdd = true;
  dialog.title = '添加角色';
};

/** 修改角色 */
const roleId = ref();
const openUpdate = async (row?: any) => {
  roleId.value = row?.roleId || ids.value[0];
  dialog.title = '修改角色';
  dialog.showUpdate = true;
};

/** 分配数据权限操作 */
const openDataScope = async (row: any) => {
  roleId.value = row?.roleId || ids.value[0];

  dialog.showDataScope = true;
  dialog.title = '分配数据权限';
};

onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
.content {
  flex: 1;
}
:deep(.content .el-card__header) {
  height: 60px;
}
:deep(.content .el-card__body) {
  height: calc(100% - 60px);
  display: flex;
  flex-direction: column;
}
</style>
